
<template>
  <div class="campus-page">
    <div class="input-card" >
			<div>操作说明：</div>
			<div>
				1：只读模式下:<span class="red">鼠标左键单击</span> 可以查看/修改当前区域信息；<span class="red"
					>鼠标右键单击</span
				>可删除当前区域及其信息。
			</div>
			<div>
				2：编辑模式下:<span class="red">鼠标左键单击</span>
				网格区域，可选中当前区域，可进行编辑区域操作，再点保存按钮结束操作。
			</div>
			<div>
				3：新建区域:点击新建按钮，通过<span class="red">鼠标左键描点</span>构建网格区域，最后以
				<span class="red">鼠标右键单击</span> 结束网格区域，最后点击保存按钮，完善信息即可完成新建功能。
			</div>
			<div class="card-flex">
				<button class="btn" v-if="type == 1" @click="type = 2">编辑模式</button>
				<button class="btn" @click="createPolygon()" v-if="type == 1">新建区域</button>
				<button class="btn" v-if="type == 2 || type == 3" @click="closePolygon()">保存</button>
				<button class="btn" v-if="type == 2" @click="type = 1">只读模式</button>
			</div>
		</div>
    <div id="campusMap"></div>
  </div>
</template>

<script>
/* eslint-disable */
import AMapLoader from "@amap/amap-jsapi-loader";
var polyEditor = "";
// let AMap = null
window.oncontextmenu = function (e) {
  e.preventDefault();
};
export default {
  props: {
    schooleName: String,
    dzName1: Array,
    visible1: Boolean,
    datas: String,
  },
  data() {
    return {
      satellite: true, //卫星地图
      flagText: true, //弹出框编辑状态
      type: 1,
      okText: "编辑", //弹出框文本
      visible: false,
      labelCol: { style: { width: "130px" } },
      formState: {
        name: "123",
      },
      rules: {
        name: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
      },
      area: "", //区域面积大小
      infoWindow: "",
      infoWindow2: "",
      pathArr: [],
    };
  },
  watch: {
  },
  mounted() {
    //DOM初始化完成进行地图初始化
    console.log(2132122, this.dzName1);
  },
  methods: {
    initData(data) {
      console.log(data);
      if (data) {
        this.pathArr = JSON.parse(data);
      }else{
        this.pathArr=[]
      }
      this.initMap();
    },
    onSubmit() {
      // this.visible2 = true;
      if (this.flagText) {
        this.flagText = false;
        this.okText = "保存";
      } else {
        this.$refs.formRef
          .validate()
          .then(async () => {
            console.log(11111);
            this.okText = "编辑";
            this.flagText = true;
          })
          .catch((error) => {
            console.log("error", error);
          });
      }
    },
    async initMap() {
      await AMapLoader.load({
        key: "a8495fcc75776a9eb1a4f3e907f0b84e", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.PolygonEditor",
          "AMap.Autocomplete",
          "AMap.PlaceSearch",
          "AMap.Scale",
          "AMap.OverView",
          "AMap.ToolBar",
          "AMap.MapType",
          "AMap.PolyEditor",
          "AMap.CircleEditor",
          "AMap.Geolocation",
          "AMap.Geocoder",
          "AMap.Polygon",
          "AMap.AMapUI",
          "AMap.InfoWindow", //新建窗体
          "AMap.GeometryUtil", //区域面积
          "AMap.TileLayer.Satellite",
        ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          this.map = new AMap.Map("campusMap", {
            //设置地图容器id
            viewMode: "3D", //是否为3D地图模式
            zoom: 15, //初始化地图级别
            disableDoubleClickZoom: false,
            // center:this.pathArr?this.pathArr[0].key[0]:''
            // center: [107.474262, 32.005631],
            center: window.location_name_school.split(',') || [116.407387,39.904179],
          });
          // 设置缩放级别最小单位为1
          // this.map.setZoom(Math.max(1, this.map.getZoom()));
          // 监听地图缩放事件
          this.map.on("zoomend", () => {
            const zoom = this.map.getZoom();
            console.log(zoom);
            // 在这里可以执行你需要的操作，比如更新数据或发送请求等
          });
          // 添加卫星图层
          if (!this.satellite) {
            const tileLayer = new AMap.TileLayer.Satellite({
              map: this.map,
            });
            tileLayer.show();
          }
          this.map.setFitView();
          // 数据格式化
          for (let q = 0; q < this.pathArr.length; q++) {
            var path = [];
            for (let w = 0; w < this.pathArr[q].key.length; w++) {
              path.push(
                new AMap.LngLat(
                  this.pathArr[q].key[w][0],
                  this.pathArr[q].key[w][1]
                )
              );
            }
            this.addPolygon(path, this.pathArr[q].timestamp);
          }
          // 创建自定义信息窗体
          this.infoWindow = new AMap.InfoWindow({
            content: this.$refs.conts, // 替换为你的自定义信息窗体内容
            // position: [116.397428, 39.90923], // 替换为你的信息窗体位置坐标点
            offset: new AMap.Pixel(0, -10), // 信息窗体相对于定位点的偏移量
          });
          this.infoWindow2 = new AMap.InfoWindow({
            content: this.$refs.conts2, // 替换为你的自定义信息窗体内容
            // position: [116.397428, 39.90923], // 替换为你的信息窗体位置坐标点
            offset: new AMap.Pixel(0, 10), // 信息窗体相对于定位点的偏移量
          });
          polyEditor = new AMap.PolygonEditor(this.map);
          this.initEditor();
          polyEditor.close();
        })
        .catch((e) => {
          console.log(e);
        });
    },
    //创建多边形-函数封装;
    addPolygon(path, id) {
      console.log(path, id);
      let that = this
      var polygon = new AMap.Polygon({
      	map: this.map,
      	path: path,
      	strokeColor: id == 2989898 ? '#FF33FF' : '#000000',
      	strokeWeight: 4,
      	strokeOpacity: 0.2,
      	fillOpacity: 0.6,
      	fillColor: '#1791fc',
      	zIndex: 50,
      	bubble: true,
      	dataForms: id
      })

      // // 多边形覆盖物上点击显示窗体;
      polygon.on('click', function (e) {
      	//打开编辑
      	if (that.type == 1) {
      		that.area = Math.round(AMap.GeometryUtil.ringArea(path))
      		that.okText = '编辑' //弹出框文本
      		that.flagText = true //弹出框编辑状态
      		that.visible = true //弹出框
      	}
      	if (that.type == 2) {
      		const { target, type, pixel } = e
      		console.log(target)
      		// 显示信息窗体
      		polyEditor.setTarget(polygon) //打开编辑
      		polyEditor.open() //打开编辑
      		that.infoWindow.close()
      	}
      })

      polygon.on('rightclick',(e)=> {
        const { target, type, pixel } = e
        console.log(target, type, pixel)
      	// console.log(JSON.stringify(e.target._opts.path)==JSON.stringify(that.pathArr[0].key), '获取参数')
      	// that.infoWindow.open(that.map, e.lnglat);//创建信息窗体
        let a=JSON.stringify(e.target._opts.path)
        if(that.type == 1) return
        that.$confirm('确定删除该区域么?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          polygon.remove();
          that.pathArr.splice(that.pathArr.findIndex(item => JSON.stringify(item.key) == a), 1)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      })
      //鼠标高亮效果
      polygon.on('mouseover', ()=> {
      	polygon.setOptions({
      		cursor: 'pointer'
      	})
      })
    },
    initEditor() {
      // add 是区域画完后鼠标右键保存事件。
      polyEditor.on("add", (data) => {
        console.log("保存", data.target._opts.path);

        //弹出模态框完善信息
        // that.infoWindow2.open(that.map, data.lnglat);
        var polygon = data.target;
        polyEditor.addAdsorbPolygons(polygon);
        console.log(987987);
        polygon.on("click", () => {
          console.log("双击", data, polygon);
          // 双击图层进行编辑
          polyEditor.setTarget(polygon);
          polyEditor.open();
        });
      });
      //end 是结束编辑按钮
      polyEditor.on("end", (data) => {
        // console.log(4444444, data);
        let obj = {
          key: data.target._opts.path,
          mapId: data.target._amap_id,
        };
        if (this.pathArr.length > 0) {
          // 判断是否有重复的点位，如果点位重复说明是修改之前的区域面积
          let isRepeat = this.pathArr.some((item, index) => {
            if (item.mapId === obj.mapId) {
              this.pathArr[index] = obj;
              return true;
            }
          });
          if (!isRepeat) {
            this.pathArr.push(obj);
          }
        } else {
          // 没有点位，直接添加
          console.log(obj, 456456);
          this.pathArr.push(obj);
        }
        console.log(this.pathArr, "最终的点位合集"); // 最终的点位合集
      });
      polyEditor.open(); // 进入组件就可以编辑
      return polyEditor;
    },
    //新建
    createPolygon() {
      this.type = 3;
      polyEditor.close();
      polyEditor.setTarget();
      polyEditor.open();
    },
    //结束编辑
    closePolygon() {
      this.visible = true;
      this.type = 1;
      // 关闭
      polyEditor.close();
    },
    //编辑
    startPolygon() {
      polyEditor.open();
    },
    campusOk() {
      polyEditor.close();
      console.log(this.pathArr.length);
      if (this.pathArr.length < 1) {
        this.$message({
          message: "请划至少划分一个区域位置！",
          type: "warning",
        });
        return;
      }
      return this.pathArr;
      // this.$emit("onPatharr", this.pathArr); // 在这里将点位合集传给父组件或者请求接口
    },
  },
};
/* eslint-disable */
</script>
<style scoped lang="scss">
#campusMap {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 750px;
  flex: 7;
  position: relative;
}

.campus-page {
  position: relative;
}

.input-card {
  color: #fff;
  width: 100%;
  display: flex;
  flex-direction: column;
  min-width: 0;
  word-wrap: break-word;
  background-clip: border-box;
  border-radius: 0.25rem;
  // width: 22rem;
  border-width: 0;
  border-radius: 0.4rem;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
  background-color: rgba(0, 0, 0, 0.8);
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
  padding: 0.75rem 1.25rem;
}

.red {
  color: red;
}

.card-flex {
  position: absolute;
  right: 20px;
  top: 20px;
  display: flex;
  justify-content: flex-end;
}

.btn {
  width: 100px;
  display: inline-block;
  font-weight: 400;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  border: 1px solid transparent;
  transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out,
    border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
  background-color: transparent;
  background-image: none;
  color: #25a5f7;
  border-color: #25a5f7;
  background-color: #25a5f7;
  color: #fff;
  padding: 0.25rem 0.5rem;
  line-height: 1.5;
  border-radius: 1rem;
  cursor: pointer;
  margin: 0 5px;
}

.btn:hover {
  color: #fff;
  background-color: #25a5f7;
  border-color: #25a5f7;
}

.btn:hover {
  text-decoration: none;
}

.title {
  border-bottom: 1px solid #ccc;
  padding-bottom: 10px;
  font-size: 18px;
}

.main {
  padding: 20px 20px;
}

:deep(.amap-info-close) {
  font-size: 24px;
  top: 15px;
  right: 17px;
}
</style>
